package com.winninghlw.windhplocalutils.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * @author water
 * 2025/3/12 9:41
 */
@Component
@Slf4j
public class HttpRestUtil {

    @Resource
    RestTemplate restTemplate;


    /**
     * get请求
     *
     * @param api 请求url
     * @return
     */
    public String getData(String api) {
        return this.getData(api, null, null);
    }
    /**
     * get请求
     *
     * @param api 请求url
     * @param reqObj 请求request实体
     * @return
     */
    public String getData(String api, Object reqObj) {
        return this.getData(api, reqObj, null);
    }

    /**
     * get请求
     *
     * @param api 请求url
     * @param reqObj 请求request实体
     * @param addHeaders 添加的头部 如需要使用jwt,key名称需设为"Bearer-Auth"
     * @return
     */
    public String getData(String api, Object reqObj, Map<String, String> addHeaders) {
        String requestUrl = api;
        // 参数处理
        if (!ObjectUtils.isEmpty(reqObj)) {
            JSONObject params = null;
            if (reqObj instanceof JSONObject) {
                params = (JSONObject) reqObj;
            } else {
                params = JSONObject.parseObject(JSON.toJSONString(reqObj, SerializerFeature.DisableCircularReferenceDetect));
            }
            //将map转换为query参数
            String queryParams = getUrlParamsByMap(params);
            if (api.contains("?")) {
                requestUrl = api + "&" + queryParams;
            } else {
                requestUrl = api + "?" + queryParams;
            }
        }
        HttpEntity<String> entity = this.getMethodHttpEntity(addHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(URI.create(requestUrl), HttpMethod.GET, entity, String.class);
        return responseEntity.getBody();
    }

    /**
     * get请求
     *
     * @param api 请求url
     * @param reqObj 请求request实体
     * @return
     */
    public byte[] getDataBytes(String api, Object reqObj) {
        String requestUrl = api;
        // 参数处理
        if (!ObjectUtils.isEmpty(reqObj)) {
            JSONObject params = null;
            if (reqObj instanceof JSONObject) {
                params = (JSONObject) reqObj;
            } else {
                params = JSONObject.parseObject(JSON.toJSONString(reqObj, SerializerFeature.DisableCircularReferenceDetect));
            }
            //将map转换为query参数
            String queryParams = getUrlParamsByMap(params);
            if (api.contains("?")) {
                requestUrl = api + "&" + queryParams;
            } else {
                requestUrl = api + "?" + queryParams;
            }
        }
        byte[] data = restTemplate.getForObject(requestUrl, byte[].class);
        return data;
    }



    /**
     * x-www-form-urlencoded的post请求
     *
     * @param requestUrl 请求url
     * @param reqObj 请求request实体
     * @return
     */
    public String postFormUrlencoded(String requestUrl, Map<String, Object> reqObj) {
        return this.postFormUrlencoded(requestUrl, reqObj, null);
    }

    /**
     * x-www-form-urlencoded的post请求
     *
     * @param requestUrl 请求url
     * @param reqObj 请求request实体
     * @param addHeaders 添加的头部 如需要使用jwt,key名称需设为"Bearer-Auth"
     * @return
     */
    public String postFormUrlencoded(String requestUrl, Map<String, Object> reqObj, Map<String, String> addHeaders) {
        HttpEntity<MultiValueMap<String, Object>> entity = this.getFormRequestHttpEntity(reqObj, MediaType.APPLICATION_FORM_URLENCODED_VALUE, addHeaders);
        String resText = restTemplate.postForObject(requestUrl, entity, String.class);
        return resText;
    }

    /**
     * json的post请求
     *
     * @param requestUrl 请求url
     * @param reqObj 请求request实体
     * @return
     */
    public String postJsonData(String requestUrl, Object reqObj) {
        return this.postJsonData(requestUrl, reqObj, null);
    }

    /**
     * json的post请求
     *
     * @param requestUrl 请求url
     * @param reqObj 请求request实体
     * @param addHeaders 添加的头部 如需要使用jwt,key名称需设为"Bearer-Auth"
     * @return
     */
    public String postJsonData(String requestUrl, Object reqObj, Map<String, String> addHeaders) {
        HttpEntity<String> entity = this.getJsonRequestHttpEntity(reqObj, addHeaders);
        String resText = restTemplate.postForObject(requestUrl, entity, String.class);
        return resText;
    }

    /**
     * 请求request实体转form-data的map
     *
     * @param reqObj 请求request实体
     * @return
     */
    public MultiValueMap<String, Object> requestBeanToFormParams(Map<String, Object> reqObj) {
        Map<String, Object> params = reqObj;
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        for (String key : params.keySet()) {
            if(params.get(key) instanceof String) {
                multiValueMap.add(key, params.get(key));
            }
        }
        return multiValueMap;
    }

    /**
     * 获取get方法的HttpEntity
     *
     * @param addHeaders 添加的头部
     * @return
     */
    public HttpEntity<String> getMethodHttpEntity(Map<String, String> addHeaders) {
        HttpHeaders headers = this.getJsonDataHttpHeaders();
        this.addHeaders(headers, addHeaders);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        return requestEntity;
    }

    /**
     * 获取form请求的HttpEntity
     *
     * @param reqObj 请求request实体
     * @param contentType form请求类型
     * @param addHeaders 添加的头部
     * @return
     */
    public HttpEntity<MultiValueMap<String, Object>> getFormRequestHttpEntity(Map<String, Object> reqObj, String contentType, Map<String, String> addHeaders) {
        HttpHeaders headers = null;
        if (MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(contentType)) {
            headers = this.getFormUrlencodedHttpHeaders();
        } else if (MediaType.MULTIPART_FORM_DATA_VALUE.equals(contentType)) {
            headers = this.getFormDataHttpHeaders();
        }
        this.addHeaders(headers, addHeaders);
        MultiValueMap<String, Object> multiValueMap = this.requestBeanToFormParams(reqObj);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multiValueMap, headers);
        return entity;
    }

    /**
     * 获取json请求的HttpEntity
     *
     * @param obj 请求request实体
     * @param addHeaders 添加的头部
     * @return
     */
    public HttpEntity<String> getJsonRequestHttpEntity(Object obj, Map<String, String> addHeaders) {
        HttpHeaders headers = this.getJsonDataHttpHeaders();
        this.addHeaders(headers, addHeaders);
        String params = null;
        if (obj instanceof JSONObject) {
            params = obj.toString();
        } else {
            params = JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
        }
        HttpEntity<String> entity = new HttpEntity<>(params, headers);
        return entity;
    }

    /**
     * 获取x-www-form-urlencoded请求头
     *
     * @return
     */
    public HttpHeaders getFormUrlencodedHttpHeaders() {
        HttpHeaders headers = this.getHttpHeaders(MediaType.APPLICATION_FORM_URLENCODED);
        return headers;
    }

    /**
     * 获取form-data请求头
     *
     * @return
     */
    public HttpHeaders getFormDataHttpHeaders() {
        HttpHeaders headers = this.getHttpHeaders(MediaType.MULTIPART_FORM_DATA);
        return headers;
    }

    /**
     * 获取json请求头
     *
     * @return
     */
    public HttpHeaders getJsonDataHttpHeaders() {
        HttpHeaders headers = this.getHttpHeaders(MediaType.APPLICATION_JSON);
        return headers;
    }

    /**
     * 获取指定mediaType请求头
     *
     * @param mediaType
     * @return
     */
    public HttpHeaders getHttpHeaders(MediaType mediaType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        return headers;
    }

    /**
     * 添加自定义的头部
     *
     * @param headers
     * @param addHeaders
     */
    public void addHeaders(HttpHeaders headers, Map<String, String> addHeaders) {
        if (addHeaders != null) {
            for (String key : addHeaders.keySet()) {
                if ("Bearer-Auth".equals(key)) {//jwt授权
                    headers.setBearerAuth(addHeaders.get(key));
                    continue;
                }
                headers.set(key, addHeaders.get(key));
            }
        }
    }

    /**
     * 将map转换成url
     *
     * @param source
     * @return 字符串
     */
    public static String getUrlParamsByMap(Map<String, Object> source) {
        Iterator<String> it = source.keySet().iterator();
        StringBuilder paramStr = new StringBuilder();
        while (it.hasNext()){
            String key = it.next();
            String value = (String) source.get(key);
            if (ObjectUtils.isEmpty(value)){
                continue;
            }
            try {
                // URL 编码
                value = URLEncoder.encode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                // do nothing
            }
            paramStr.append("&").append(key).append("=").append(value);
        }
        // 去掉第一个&
        return paramStr.substring(1);
    }

}
